// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.

function html_unescape(text) {
    // Unescape a string that was escaped using django.utils.html.escape.
    text = text.replace(/&lt;/g, '<');
    text = text.replace(/&gt;/g, '>');
    text = text.replace(/&quot;/g, '"');
    text = text.replace(/&#39;/g, "'");
    text = text.replace(/&amp;/g, '&');
    return text;
}

// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct 
// element when the popup window is dismissed.
function id_to_windowname(text) {
    text = text.replace(/\./g, '__dot__');
    text = text.replace(/\-/g, '__dash__');
    return text;
}

function windowname_to_id(text) {
    text = text.replace(/__dot__/g, '.');
    text = text.replace(/__dash__/g, '-');
    return text;
}

function showRelatedObjectLookupPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^lookup_/, '');
    name = id_to_windowname(name);
    var href;
    if (triggeringLink.href.search(/\?/) >= 0) {
        href = triggeringLink.href + '&pop=1';
    } else {
        href = triggeringLink.href + '?pop=1';
    }
    var win = window.open(href, name, 'height=800,width=1200,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        document.getElementById(name).value = chosenId;
        if(name == 'id_sub_info'){
        	$.getJSON("/get_sub/", {'id': chosenId}, function(data){
        		$("#id_sub_info_req").html(data.res);
        		$("#id_sub_info_req").attr('href', '/admin/sub_info/subinfo/' + chosenId + '/').attr('title', 'click to view detail').attr('data-id', chosenId);
        	});
        }else if(name == 'id_rej'){
			$.getJSON("/get_rej/", {'id': chosenId}, function(data){
				$("#id_rej_id").html(data.res);
				$("#id_rej_id").attr('href', '/admin/sub_info/rejection/' + chosenId + '/').attr('title', 'click to view detail').attr('data-id', chosenId);
			});      	
        }else if(name == 'id_app'){
	        $.getJSON("/get_app_name/", {'id': chosenId}, function(data){
	        	$("#id_now_name").html("");
	        	$("#id_app_name").html(data.res);
	        	$("#id_app_name").attr('href', '/admin/app_info/app/' + chosenId + '/').attr('title', 'click to view detail').attr('data-id', chosenId);
	        });
	        if($("div.field-rating ").length != 0){
	        	$.getJSON("/get_rating/", {'id': chosenId}, function(data){
	        		var html = "<option value=''>---------</option>";
	        		$.each(data.res, function(k, v){
	        			html += "<option value='" + v + "'>" + v + "</option>";
	        		});
	        		$("#select_rating").html(html);
	        	});
	        }
	        if($("#id_version").length != 0){
	        	$.getJSON("/get_version/", {'id': chosenId, 'status': $("#chosen_status").val()}, function(data){
	        		var html = "<option value=''>---------</option>";
	        		$.each(data.res, function(k, v){
	        			if(v == $("#id_version").val()){
	        				html += "<option selected='selected' value='" + v + "'>" + v + "</option>";
	        			}else{
		        			html += "<option value='" + v + "'>" + v + "</option>";
	        			}
	        		});
	        		$("#select_version").html(html);
	        	});
	        }
        }
        if($("td.field-type").length != 0){
        	$.getJSON("/get_iap_type/", {'id': chosenId}, function(data){
        		if(data.res == ''){
        			$("td.field-type > select").css('display', 'none');
        			$("td.field-type > input").css('display', 'block');
        		}else{
        			$("td.field-type > select").css('display', 'block');
        			$("td.field-type > input").css('display', 'none');
	        		var html = "<option value=''>---------</option>";
	        		$.each(data.res, function(k, v){
        				html += "<option value='" + v + "'>" + v + "</option>";
	        		})
	        		$("td.field-type > select").html(html);
        		}
        		$("td.field-prd_id > input").val(data.bundle_id.replace(/-/g, '_') + ".");
        	});
        }
    }
    win.close();
}

function showAddAnotherPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    href = triggeringLink.href
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

function dismissAddAnotherPopup(win, newId, newRepr) {
    // newId and newRepr are expected to have previously been escaped by
    // django.utils.html.escape.
    newId = html_unescape(newId);
    newRepr = html_unescape(newRepr);
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem) {
        var elemName = elem.nodeName.toUpperCase();
        if (elemName == 'SELECT') {
            var o = new Option(newRepr, newId);
            elem.options[elem.options.length] = o;
            o.selected = true;
        } else if (elemName == 'INPUT') {
            if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                elem.value += ',' + newId;
            } else {
                elem.value = newId;
            }
        }
    } else {
        var toId = name + "_to";
        elem = document.getElementById(toId);
        var o = new Option(newRepr, newId);
        SelectBox.add_to_cache(toId, o);
        SelectBox.redisplay(toId);
    }
    win.close();
}
